// pages/enterprise/enterpriseCont/enterpriseCont.js

var app = getApp();
import SDK from "../../../IMJS/NIM_Web_SDK_weixin_v6.2.0";
import {
    ajaxPost,
    showToast,
} from "../../../utils/util.js";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        WEBURL: app.globalData.WEBURL, // 背景图域名
        contId: "", //企业id
        companyId: "", //招聘会id
        hallRoomId: "", //大厅聊天室id
        roomSource: {}, //房间信息
        companyIsOnline: 1, // 招聘者是否在线
        scrollHeight: 0, // 聊天内容 总共高度
        companyListHeight: 0, // 更多企业 scroll-view高度
        loginUser: {}, // 当前用户 网易信息
        firstSource: {}, // 上麦者
        firstTime: 300, // 上麦者剩余时间
        rankingSource: [], // 排麦队列

        companyListShow: false, // 更多企业是否展示 false =》不展示 true =》展示
        hallCompanySource: [], //更多企业列表
        popupShow: false, // 弹窗里面是否显示 false=>不显示
        recruitShow: false, // 招聘详情是否显示 false=>不显示
        popupVal: 2, // 弹窗里面显示第几个
        companySource: {}, // 弹窗公司详情
        recruitSource: {}, // 招聘列表
        companyHot: [], // 推荐公司


        lobbyInviteTime: 0, // 推广消息剩余时间
        muted: true, // 麦克风是否静音 
        playVoice: false, // 播放声音是否静音 
        privacyVal: false, // 隐私控制 
        footerShow: true, // 操作与输入框切换

        emojiShow: false, // 表情是否显示 false=>不显示
        inputValue: "",
        chatType: "team",
        selectRoomVal: "small", //控制输入框失去焦点与否
        focusFlag: false, //控制输入框失去焦点与否
        emojiFlag: false, //emoji键盘标志位
        moreFlag: false, // 更多功能标志
        scrollTop: 0, // 聊天内容 高度位置
        smallNewsArr: [], //房间聊天室信息储存
        hallNewsArr: [], //房间聊天室信息储存
        userlist: []
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.setKeepScreenOn({
            keepScreenOn: true
        });
        // 设置 scroll-view高度
        let windowHeight = wx.getSystemInfoSync().windowHeight; // 屏幕的高度
        let windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕的宽度
        this.setData({
            contId: options.id,
            companyId: options.companyid,
            hallRoomId: options.hallRoomId,
            scrollHeight: (windowHeight * 750) / windowWidth - 766 - 30,
            companyListHeight: (windowHeight * 750) / windowWidth - 92
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getSmallRoomConfig();
        this.hallRoomConfig();
        this.listenNetcallEvent();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(this.noticeTime);
        clearInterval(this.Heart);
        clearInterval(this.RoomQueue);
        wx.setKeepScreenOn({
            keepScreenOn: false
        });
        console.error('退出2');
        wx.navigateBack();
        console.log('返回上一页');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.Heart);
        clearInterval(this.RoomQueue);
        this.exitRoom();

        app.globalData.hallRoom.disconnect();
        app.globalData.smallRoom.disconnect();
        // 音频聊天室退出
        app.globalData.netcall.leaveChannel().then(() => {
            // 清除上层UI逻辑
            console.log("-------->音频聊天室退出");
        });
    },
    /**
     * 获取房间信息
     */
    getSmallRoomConfig() {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
            company_uid: that.data.companyId
        };
        ajaxPost("/meeting/roominfo", data, res => {
            if (res.code == 0) {
                let {
                    time,
                    is_me
                } = res.data.first_user;
                if (!time) {
                    time = 0;
                }
                if (res.data.is_hide == 2 && is_me == 0) {
                    var content = {
                        type: 'company',
                        privacyVal: 2,
                        nick: res.data.company_name,
                        text: '我有几个隐私问题要问这位同学，大家将暂时听不见我们的谈话，请大家稍等一下～',
                        account: res.data.company_logo,
                    };
                    that.setData({
                        smallNewsArr: [...that.data.smallNewsArr, content],
                    });
                    this.setData({
                        privacyVal: true,
                    })
                }
                /**
                 * 判断是否可以弹出公告窗口
                 */
                if (that.data.noticeShow) {
                    let viewHeight;
                    wx.createSelectorQuery().selectAll('.notice').boundingClientRect(function (rect) {
                        viewHeight = rect[0].height
                        that.setData({
                            scrollHeight: that.data.scrollHeight - (viewHeight * 2) - 40
                        })
                    }).exec()
                    this.noticeTime = setTimeout(() => {
                        that.setData({
                            scrollHeight: that.data.scrollHeight + (viewHeight * 2) + 40,
                            noticeShow: false,
                        })
                    }, app.globalData.noticeTimeNum);
                }
                that.setData({
                    roomSource: res.data,
                    rankingSource: res.data.user_list,
                    firstSource: res.data.first_user,
                    firstTime: time
                });

                if (is_me == 1) {
                    that.startspeak();
                }
                this.Heart = setInterval(() => {
                    this.getHeart();
                }, 1000);
                this.getRoomQueue();
                this.RoomQueue = setInterval(() => {
                    this.getRoomQueue();
                }, 5000);
                /**
                 * 判断是否有音频房间id
                 */
                console.error("is_vroomid----->", !res.data.vroomid);
                if (!res.data.vroomid) {
                    clearInterval(this.Heart);
                    showToast("text", "音频房间未创建 ，请重试");
                    app.globalData.hallRoom.disconnect();
                    console.error('退出4');
                    setTimeout(() => {
                        wx.navigateBack()
                    }, 2000);
                } else {
                    that.voiceConfig();
                }
                that.smallRoomConfig();
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /**
     * 房间心跳
     */
    getHeart() {
        let _this = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: _this.data.contId,
            company_uid: _this.data.companyId
        };
        ajaxPost("/meeting/roomHeartbeat", data, res => {
            if (res.code == 0) {
                let {
                    my_uid,
                    first_uid,
                    time
                } = res.data;
                console.log(Number(my_uid) == Number(first_uid));
                console.log(Number(my_uid) == Number(first_uid) && time == 300);
                if (Number(my_uid) == Number(first_uid) && time == 300) {
                    console.log('this.data.muted', this.data.muted);
                    if (!this.data.muted) {
                        app.globalData.netcall.switchMode(1).then(() => {
                            console.error('上麦成功');
                            showToast('text', '上麦成功')
                            this.startspeak();
                            this.setData({
                                muted: true
                            });
                        }).catch(err => {
                            showToast('text', '上麦失败,请退出房间重试')
                        });
                    }
                }
                if (my_uid == first_uid && time < 1) {
                    console.error('退出1');
                    this.exitRoom();
                    wx.navigateBack();
                }
                if (this.data.firstSource.uid !== first_uid) {
                    this.getRoomQueue();
                }
                this.setData({
                    firstTime: time
                });
            }
        });
    },
    /**
     * 排队信息
     */
    getRoomQueue() {
        let that = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
            company_uid: that.data.roomSource.company_uid
        };
        ajaxPost("/meeting/roomQueue", data, res => {
            if (res.code == 0) {
                if (res.data.first_user.length !== 0) {
                    this.setData({
                        companyIsOnline: res.data.company_is_online,
                        firstSource: res.data.first_user,
                        rankingSource: res.data.list,
                        firstTime: res.data.first_user.time
                    });
                } else {
                    this.setData({
                        firstSource: [],
                        rankingSource: [],
                        firstTime: 0
                    });
                }
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /**
     * 企业房间聊天室加入
     */
    smallRoomConfig() {
        let that = this;
        app.globalData.nim.getChatroomAddress({
            chatroomId: this.data.roomSource.roomid,
            done: getChatroomAddressDone
        });

        function getChatroomAddressDone(error, data) {
            app.globalData.smallRoom = SDK.Chatroom.getInstance({
                debug: false,
                appKey: app.globalData.appkey,
                token: app.globalData.wytoken,
                account: app.globalData.account,
                chatroomAddresses: data.address,
                chatroomId: data.chatroomId,
                onconnect: that.onChatroomConnect,
                onerror: that.onChatroomError,
                onwillreconnect: that.onChatroomWillReconnect,
                ondisconnect: that.onChatroomDisconnect,
                // 消息
                onmsgs: that.onChatroomMsgs
            });
        }
    },
    /**
     * 大厅聊天室加入
     */
    hallRoomConfig() {
        let that = this;
        app.globalData.nim.getChatroomAddress({
            chatroomId: this.data.hallRoomId,
            done: getChatroomAddressDone
        });

        function getChatroomAddressDone(error, data) {
            app.globalData.hallRoom = SDK.Chatroom.getInstance({
                debug: false,
                appKey: app.globalData.appkey,
                token: app.globalData.wytoken,
                account: app.globalData.account,
                chatroomAddresses: data.address,
                chatroomId: data.chatroomId,
                onconnect: that.onChatroomConnect,
                onerror: that.onChatroomError,
                onwillreconnect: that.onChatroomWillReconnect,
                ondisconnect: that.onChatroomDisconnect,
                // 消息
                onmsgs: that.onChatroomMsgs
            });
        }
    },
    /**
     * 连接上服务器
     */
    onChatroomConnect(chatroomInfo) {
        if (chatroomInfo.chatroom.id == this.data.hallRoomId) {
            showToast('text', '加入大厅聊天室成功')
            console.log('加入大厅聊天室成功');
        } else {
            app.globalData.smallRoom.getChatroom({
                done: getChatroomDone
            });

            function getChatroomDone(error, obj) {
                console.error('获取房间聊天室成功' + (!error ? '成功' : '失败'), error, obj);
            }
            console.log('加入房间聊天室成功');
            showToast('text', '加入房间聊天室成功')
        }
    },
    /**
     * 发生错误
     */
    onChatroomError(error, obj) {
        this.pageTimer = setTimeout(() => {
            wx.showToast({
                title: "连接已断开,即将返回",
                duration: 2000,
                success: function () {
                    this.exitRoom();
                }
            });
        }, 200);
    },
    /**
     * 即将重连
     */
    onChatroomWillReconnect(obj) {
        console.log(`onwillreconnect-${app.globalData.reconnectionAttempts}`, obj);
    },
    /**
     * 已经断开连接
     */
    onChatroomDisconnect(error) {
        console.log("ondisconnect", error);
        if (error.code == 'kicked' && error.reason == 'managerKick') {
            this.byKick();
        }
    },
    /**
     * 收到消息
     */
    onChatroomMsgs(msgs) {
        console.log("onChatroomMsgs", msgs);
        let that = this;
        msgs.map(msg => {
            switch (msg.type) {
                case "notification": {
                    that.addNotificationToRender(msg);
                    break;
                }
                case "text": {
                    that.addTextToRender(msg);
                    break;
                }
                case "custom": {
                    that.addCompanyNews(msg);
                    break;
                }
            }
        });
        // 滚动到底部
        that.scrollToBottom();
    },
    /**
     * 添加通知消息到渲染队列中
     */
    addNotificationToRender(msg) {
        // 添加到渲染队列
        if (!msg.text) {
            return;
        }
        let {
            hallRoomId
        } = this.data;
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msg.from,
            nick: msg.attach.fromNick,
            text: msg.text,
            type: msg.attach.type
        };
        if (msg.chatroomId !== hallRoomId) {
            this.setData({
                smallNewsArr: [...this.data.smallNewsArr, msgData]
            });
        }
        if (msg.chatroomId == hallRoomId) {
            this.setData({
                hallNewsArr: [...this.data.hallNewsArr, msgData]
            });
        }
    },
    /**
     * 添加文本(包含emoji)消息到渲染队列中
     */
    addTextToRender(msg) {
        let {
            hallRoomId
        } = this.data;
        if (!msg.text) {
            return;
        }
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msg.from,
            nick: msg.fromNick,
            text: msg.text,
            type: msg.type,
        };
        if (msg.chatroomId !== hallRoomId) {
            this.setData({
                smallNewsArr: [...this.data.smallNewsArr, msgData]
            });
        }
        if (msg.chatroomId == hallRoomId) {
            this.setData({
                hallNewsArr: [...this.data.hallNewsArr, msgData]
            });
        }

        this.scrollToBottom();
    },
    /**
     *  企业信息添加
     * @param {*} msg 
     */
    addCompanyNews(msg) {
        let that = this
        console.log('321321');
        let {
            hallRoomId
        } = this.data;
        let msgCont = JSON.parse(msg.content);
        if (!!msgCont.privacyVal) {
            /**
             * 1 公开  2 隐私
             */
            if (msgCont.privacyVal == 1) {
                that.setData({
                    privacyVal: false
                });
            } else if (msgCont.privacyVal == 2 && this.data.firstSource.is_me !== 1) {
                that.setData({
                    privacyVal: true
                });
            }

        }
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msgCont.account,
            nick: msgCont.nick,
            text: msgCont.text,
            type: msgCont.type,
        };
        if (msg.chatroomId !== hallRoomId) {
            this.setData({
                smallNewsArr: [...this.data.smallNewsArr, msgData]
            });
        }
        if (msg.chatroomId == hallRoomId) {
            this.setData({
                hallNewsArr: [...this.data.hallNewsArr, msgData]
            });
        }

        this.scrollToBottom();
    },
    /**
     * 被招聘者通知结束通话
     */
    byKick() {
        showToast('text', '招聘者与您结束了通话', {
            duration: 1000
        });
        console.error('退出5');
        setTimeout(() => {
            wx.navigateBack()
        }, 1000);
    },
    /**
     * 滚动聊天内容到底部
     */
    scrollToBottom: function () {
        var smallLen = this.data.smallNewsArr.length; //遍历的数组的长度
        var hallLen = this.data.hallNewsArr.length; //遍历的数组的长度
        if (this.data.selectRoomVal == "small") {
            this.setData({
                smallScrollTop: 1000 * smallLen,
            });
        } else {
            this.setData({
                hallScrollTop: 1000 * hallLen // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
            });
        }
    },
    /**
     * 音频房间加入
     */
    voiceConfig() {
        let {
            roomSource,
            firstSource
        } = this.data;
        let channelName = roomSource.vroomid;
        console.error(channelName);
        let that = this;
        app.globalData.netcall.joinChannel({
                mode: firstSource.is_me == 1 ? 1 : 3,
                channelName: channelName,
                role: 0
            })
            .then(data => {
                console.error(firstSource.is_me == 1 ? true : false);
                console.error('加入音频房间成功');
                that.setData({
                    muted: firstSource.is_me == 1 ? true : false,
                    loginUser: {
                        uid: data.uid,
                        cid: data.cid,
                        account: data.account
                    }
                });
                that.livePusherContext = wx.createLivePusherContext();
            })
            .catch(error => {
                this.newVoiceConfig(channelName);
            });
    },
    /**
     * 如果没有音频房间 就创建音频房间
     */
    newVoiceConfig(channelName) {
        app.globalData.netcall.createChannel({
                channelName: channelName
            })
            .then(data => {
                that.voiceConfig()
            })
    },
    /**
     * 排麦开始
     */
    startspeak() {
        console.error('排麦开始');
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: this.data.contId,
            company_uid: this.data.companyId
        };
        ajaxPost("/meeting/startspeak", data, res => {
            if (res.code == 0) {

            } else if (res.code == 40002) {
                showToast("error", res.msg);
                console.error('退出3');
                setTimeout(() => {
                    wx.navigateBack()
                }, 2000);
            } else {
                showToast("error", res.msg);
            }
        });
    },
    /**
     * 退出房间
     */
    exitRoom() {
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: this.data.contId,
            company_uid: this.data.companyId
        };
        ajaxPost("/meeting/exitRoom", data, res => {
            if (res.code == 0) {} else {
                showToast("error", res.msg);
            }
        });
    },
    listenNetcallEvent() {
        let that = this;
        app.globalData.emitter.on("syncDone", data => {
            that.setData({
                userlist: data.userlist
            });
            that.getRoomQueue();
            that.reconnectStreamAfter();
        });
        app.globalData.emitter.on("clientLeave", data => {
            that.getRoomQueue();
            console.log("有人离开了，离开前：");
            console.log(that.data.userlist);
            that._personLeave(data);
            console.log("有人离开了，离开后：");
            console.log(that.data.userlist);
        });
        app.globalData.emitter.on("clientJoin", data => {
            console.log("有人加入了1");
            that.getRoomQueue();
            console.log("有人加入了2");
            that._personJoin(data);
            console.log(that.data.userlist);
        });
        app.globalData.emitter.on("joinChannel", data => {
            let userlist = Object.assign([], this.data.userlist);
            userlist.map(user => {
                if (user.account === data.account) {
                    user.uid = data.uid;
                }
            });
            that.setData({
                userlist
            });
        });
        // 信令准备重连
        app.globalData.emitter.on("willreconnect", () => {
            this.stopStream();
        });
    },
    _personJoin(data) {
        let updateUserlist = Object.assign([], this.data.userlist);
        updateUserlist.push(data);
        console.error("updateUserlist1---->", updateUserlist);
        this.setData({
            userlist: updateUserlist
        });
    },
    _personLeave(data) {
        let userlist = Object.assign([], this.data.userlist);
        userlist.map((user, index) => {
            if (user.uid === data.uid) {
                let player = this._getPlayerComponent(data.uid);
                if (player) {
                    player.stop();
                }
                user.url = "";
            }
        });
        this.setData({
            userlist
        });
    },

    /**
     * 返回指定uid组件的拉流操作上下文
     */
    _getPlayerComponent(uid) {
        const yunxinPlayer = this.selectComponent(`#yunxinplayer-${uid}`);
        return yunxinPlayer;
    },
    stopStream(duration = 1000) {
        if (this.stopStreamTimer) {
            clearTimeout(this.stopStreamTimer);
        }
        if (this.data.streamStoped) {
            return Promise.resolve();
        }
        console.log("停止推流");
        return new Promise((resolve, reject) => {
            this.stopStreamTimer = setTimeout(() => {
                if (!this.livePusherContext) {
                    return;
                }
                if (!this.livePlayerMap) {
                    this.livePlayerMap = {};
                }
                this.data.userlist.map(user => {
                    const uid = `${user.uid}`;
                    console.log(`停止拉流 ${uid}`);
                    if (!this.livePlayerMap[uid]) {
                        this.livePlayerMap[uid] = wx.createLivePlayerContext(
                            `yunxinplayer-${uid}`,
                            this
                        );
                    }
                    this.livePlayerMap[uid].stop();
                });
                this.livePusherContext.stop({
                    complete: () => {
                        console.log("推流已停止");
                        this.setData({
                            streamStoped: true
                        });
                        resolve();
                    }
                });
            }, duration);
        });
    },
    reconnectStream() {
        if (this.data.streamNeedReconnect) {
            clearTimeout(this.stopStreamTimer);

            console.log("开始推流");
            console.log("this.userlist", this.data.userlist);
            this.livePusherContext.start({
                success: () => {
                    this.setData({
                        streamStoped: false
                    });
                },
                complete: () => {
                    if (!this.livePlayerMap) {
                        this.livePlayerMap = {};
                    }
                    this.data.userlist.map(user => {
                        const uid = `${user.uid}`;
                        console.error(`重新播放 ${uid}`);
                        console.log(user);
                        if (!this.livePlayerMap[uid]) {
                            this.livePlayerMap[
                                uid
                            ] = wx.createLivePlayerContext(
                                `yunxinplayer-${uid}`,
                                this
                            );
                        }
                        this.livePlayerMap[uid].play();
                    });
                }
            });
        }
    },
    reconnectStreamAfter(duration = 0) {
        clearTimeout(this.reconnectStreamTimer);
        this.reconnectStreamTimer = setTimeout(() => {
            this.reconnectStream();
        }, duration);
    },
    /**
     * ----------------------------->页面操作逻辑<------------------------
     */

    /**
     * 键盘单击发送，发送文本
     */
    inputSend(e) {
        this.setData({
            emojiShow: false,
        })
        this.sendRequest(this.data.inputValue);
    },
    /**
     * 选择房间
     */
    selectRoom(e) {
        let type = e.currentTarget.dataset.type;
        if (this.data.selectRoomVal !== type) {
            this.setData({
                selectRoomVal: type
            });
        }
    },
    /**
     * 文本框输入事件
     */
    inputChange(e) {
        this.setData({
            inputValue: e.detail.value
        });
    },
    /*
     * 发送网络请求：发送文本消息(包括emoji)
     */
    sendRequest(text) {
        let _this = this;
        if (text == "") {
            showToast("text", "输入内容不能为空");
            return;
        }
        let Sender;
        if (this.data.selectRoomVal == "small") {
            Sender = app.globalData.smallRoom;
        } else {
            Sender = app.globalData.hallRoom;
        }
        Sender.sendText({
            text,
            done: (err, msg) => {
                if (err) {
                    return;
                }
                _this.setData({
                    inputValue: ""
                });
                // 刷新界面
                _this.addTextToRender(msg);
                // 滚动到底部
                _this.scrollToBottom();
            }
        });
    },
    /**
     * 暂未完善
     */
    maintain() {
        showToast('text', '正在努力开发中，请等待后续版本更新。')
    },

    /**
     * 控制更多企业列表是否显示
     */
    selectcompanyListShow(e) {
        if (e.currentTarget.dataset.show == 'true') {
            this.getMeetingInfo();
        } else {
            this.setData({
                companyListShow: false
            })
        }
    },
    /**
     * 获取当前会场信息
     */
    getMeetingInfo() {
        let that = this
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: that.data.contId,
        };
        ajaxPost("/meeting/meetinginfo", data, function (res) {
            if (res.code == 0) {
                that.setData({
                    companyListShow: true,
                    hallCompanySource: res.data.company_total,
                })
            } else {
                showToast('text', res.msg)
            }
        });
    },
    /**
     * 输入框和操作按钮切换
     */
    emojiControl() {
        this.setData({
            footerShow: !this.data.footerShow,
            emojiShow: true,
            moreFlag: false,
        })
    },
    /**
     * 输入框和操作按钮切换
     */
    footetControl() {
        if (!this.data.footerShow) {
            this.setData({
                footerShow: !this.data.footerShow,
                emojiShow: false,
                focusFlag: false,
            })
        } else {
            this.setData({
                footerShow: !this.data.footerShow,
                emojiShow: false,
                focusFlag: true,
            })
        }

    },
    /**
     * 播放音频控制
     */
    voiceControl() {
        if (this.data.playVoice) {
            showToast('text', `播放声音已打开`)
        } else {
            showToast('text', `播放声音已关闭`)
        }
        this.setData({
            playVoice: !this.data.playVoice
        })
    },
    /**
     * 麦克风控制
     */
    microphoneControl() {
        if (!this.data.muted) {
            showToast('text', '麦克风已打开')
        } else {
            showToast('text', '麦克风已关闭')

        }
        this.setData({
            muted: !this.data.muted
        })
    },
    /**
     *  查看当前企业详情
     * @param {e} e 
     */
    lookCompanyInfo() {
        this.getCompanyInfo(this.data.companyId)

    },
    /**
     *  查看企业详情
     * @param {e} e 
     */
    companySelect(e) {
        let data = e.currentTarget.dataset.data
        if (!data) {
            this.setData({
                popupVal: 2,
                recruitShow: false,
                popupShow: false
            })
            return;
        }
        this.getCompanyInfo(data.company_uid)

    },
    /**
     * 招聘信息详情弹窗切换
     */
    lookRecruitCont(e) {
        const {
            index,
            showval
        } = e.target.dataset
        if (showval) {
            let newWorkSource = this.data.recruitSource[index]
            this.setData({
                workSource: newWorkSource,
                recruitShow: true
            })
        } else {
            this.setData({
                recruitShow: false
            })
        }

    },
    /**
     * 弹窗选择第几个显示
     * @param {穿参第几个} e 
     */
    popupTitleSelect(e) {
        let index = e.currentTarget.dataset.index
        if (this.popupVal !== index) {
            this.setData({
                popupVal: index
            })
        }
    },
    /**
     * 获取企业信息
     */
    getCompanyInfo(id) {
        console.log(id);
        let _this = this
        let data = {
            token: wx.getStorageSync("token"),
            company_uid: id,
        };
        ajaxPost("/company/companyInfo", data, function (res) {
            if (res.code == 0) {
                _this.setData({
                    popupShow: true,
                    companySource: res.data.company_data,
                    recruitSource: res.data.position_list,
                })
            } else {
                showToast('text', res.msg)
            }
        });
    },
    /**
     *  详情内投递简历
     * @param {*} e 
     */
    workSend(e) {
        const {
            is
        } = e.target.dataset
        const {
            workSource
        } = this.data
        if (is == 1) {
            showToast('text', '已经投递过了');
            return;
        }
        let data = {
            token: wx.getStorageSync('token'),
            position_id: workSource.id
        }
        ajaxPost('/company/sendresume', data, (res) => {
            if (res.code == 0) {
                this.getCompanyInfo(workSource.uid)
                let newWorkSource = workSource
                newWorkSource.is_send_resume = 1
                this.setData({
                    workSource: newWorkSource
                })
                showToast('text', '投递成功');
            } else {
                showToast('text', res.msg);
            }
        })
    },
    /**
     * 投递简历
     */
    send(e) {
        let index = e.target.dataset.index
        let resume = this.data.recruitSource[index]
        if (resume.is_send_resume == 1) {
            showToast('text', '已经投递过了');
        } else {
            let data = {
                token: wx.getStorageSync('token'),
                position_id: resume.id
            }
            ajaxPost('/company/sendresume', data, (res) => {
                if (res.code == 0) {
                    let newresume = this.data.recruitSource
                    newresume[index].is_send_resume = 1
                    this.setData({
                        recruitSource: newresume
                    })
                    showToast('text', '投递成功');
                } else {
                    showToast('text', res.msg);

                }
            })
        }
    },
    /**
     * 切换房间
     */
    goSmallRoom() {
        let roomInfo = this.data.companySource
        let data = {
            token: wx.getStorageSync("token"),
            company_uid: roomInfo.uid,
        };
        ajaxPost("/company/companyInfo", data, (res) => {
            if (res.code == 0) {
                if (res.data.company_data.is_online == 0) {
                    showToast('text', '招聘者暂时不在，请稍后再试');
                    return;
                }
                if (res.data.student_count >= 10) {
                    showToast('text', '该房间以爆满，请选择其他房间重试');
                    return;
                }
                app.globalData.hallRoom.disconnect();
                app.globalData.smallRoom.disconnect();
                app.globalData.netcall.leaveChannel().then(() => {
                    console.log("-------->音频聊天室退出");
                    this.setData({
                        popupVal: 2,
                        recruitShow: false,
                        popupShow: false
                    })
                    wx.redirectTo({
                        url: '/pages/student/smallRoom/smallRoom?id=' + this.data.contId + '&hallRoomId=' + this.data.hallRoomId + '&companyid=' + roomInfo.uid
                    })

                });


            } else {
                showToast('text', res.msg)
            }
        });
    },
    /**
     * 表情添加
     */
    emojiAdd(e) {
        console.log('hall', e);
        this.setData({
            inputValue: this.data.inputValue + e.detail.emoji
        })
    },
    /**
     * 表情显示隐藏控制
     */
    emojiClick() {
        this.setData({
            emojiShow: !this.data.emojiShow
        })
    }
});